package com.zetor.ms.core.util;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.stereotype.Component;

import java.util.Locale;

/**
 * 消息打印工具类
 *
 * @author zlc
 * @version 1.0.0
 * @date 2021/6/15 10:47
 */
@Component
public class MsgUtils {
    private static MessageSource messageSource;
    private static final String EXCEPTION = "java.lang.Exception";
    private static final String FILE_EXP = "exp";

    private static final Logger log = LoggerFactory.getLogger(MsgUtils.class);

    @Autowired
    public MsgUtils(MessageSource msgSource) {
        MsgUtils.messageSource = msgSource;
    }

    /**
     * log print
     *
     * @param key
     * @param args
     * @return
     */
    private static String getMsg(String key, Locale l, String... args) {
        if (StringUtils.isBlank(key)) {
            return "";
        }
        return messageSource.getMessage(key, args, l);
    }


    /**
     * log print, 支持可变参数
     *
     * @param key  msgCode 参考【messages.properties】配置文件
     * @param args
     * @return
     */
    public static String get(String key, String... args) {
        return getMsg(key, Locale.getDefault(), args);
    }

    /**
     * log print
     *
     * @param key msgCode 参考【messages.properties】配置文件
     * @return
     */
    public static String get(String key) {
        return getMsg(key, Locale.getDefault(), null);
    }

    /**
     * log print
     *
     * @param key msgCode 参考【messages_exp.properties】配置文件
     * @return
     */
    public static String getExp(String key) {
        return getExp(key, null);
    }

    /**
     * log print for exp
     *
     * @param key  msgCode 参考【messages_exp.properties】配置文件
     * @param args
     * @return
     */
    public static String getExp(String key, String... args) {
        String msg = "";
        try {
            msg = getMsg(key, new Locale(FILE_EXP, ""), args);
        } catch (NoSuchMessageException e) {
            log.error(e.getMessage());
            msg = getMsg(EXCEPTION, new Locale(FILE_EXP, ""), args);
        }
        return msg;
    }


    public static void main(String[] args) throws Exception {
        System.out.println(MsgUtils.getExp("java.text.ParseException"));

    }
}
